import datetime
import time
import re
from smbclient import *
import signal, os


PATH = "/232_INBOX/PROMOS_TO_TIBA_BRASIL/"
FILE_NAME = "service"


last_run = 131644000
loop     = True


def strToUnixTime(strtime = None):
        if strtime == None:
                return -1

        lst = re.split(' ', strtime)
        strtime = lst[0] + ' ' + lst[1] + ' ' + lst[2] + ' ' + lst[3] + ' ' + lst[4] + ' ' + lst[5] + ' ' + lst[6]
        d = datetime.datetime.strptime(strtime, "%a %d %b %Y %I:%M:%S %p %Z")
        return int(time.mktime(d.timetuple()))


def getRemoteTime(smb = None, remotepath = '/', localpath = '/tmp/' , localfile = 'service.wf'):
	if smb != None:
		f = open(localpath + localfile, "w")
		f.write("WF")	
		f.close()
		smb.upload(localpath + localfile, remotepath + localfile)
		info = smb.info(remotepath + localfile)
		smb.unlink(remotepath + localfile)
		os.unlink(localpath + localfile)
		return strToUnixTime(info['create_time'])
	else:
		return -1
		
def getNewFiles(smb = None, remotepath = '/', local_time = 0, remote_time =0, last_run = 0 ):
	newfiles = []	

	if smb != None:
		diff_sync = local_time - remote_time

		if (last_run - diff_sync) < 0:
			condition = last_run
		else:
			condition = last_run - diff_sync
	
	lst = smb.listdir(remotepath)
	for f in lst:
		info = smb.info(remotepath + f)
		create_time = strToUnixTime(info['create_time'])

		if ( create_time > condition ):
			newfiles.append(f)
	
	return newfiles


smb = SambaClient(server="10.221.40.231", share="RHOZET", username='mxfuser', password='Fl@cIplusb')




try:
	while loop:
	
		remote_time = getRemoteTime(smb, PATH, './', FILE_NAME)
		local_time  = int(time.time())
	
		
		print "Remote time: " + str(remote_time)
		print "Local time: "  + str(local_time)
	
		l = getNewFiles(smb, PATH, local_time, remote_time, last_run)
		
		for i in l:
			print i
	
		last_run = local_time
		time.sleep(10)	
except KeyboardInterrupt, e:
	print "Teclado"
	print e
